package pl.diagnoser.client.tools;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;


import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class SearchObjectAttribute implements Serializable {
	
	private static final long serialVersionUID = 1L;
	private String attributeName;
	private Double confidence;
	private ArrayList<String> attributeValues = new ArrayList<String>();
	
	public SearchObjectAttribute() {}
	public SearchObjectAttribute(String attributeName) {
		this.attributeName = attributeName;
	}
	
	public String getAttributeName() {
		return attributeName;
	}
	public void setAttributeName(String attributeName) {
		this.attributeName = attributeName;
	}
	
	public Double getConfidence() {
		return confidence;
	}
	
	public void setConfidence(Double confidence) {
		this.confidence = confidence;
	}
	
	public ArrayList<String> getAttributeValues(boolean md5) {
		ArrayList<String> tmpValues = new ArrayList<String>();
		if(md5) {
			for(String tmpValue : attributeValues)
				tmpValues.add(convertAttributeValue(tmpValue));
		} else
			tmpValues = attributeValues;
		
		return tmpValues;
	}
	public void setAttributeValues(ArrayList<String> attributeValues) {
		this.attributeValues = attributeValues;
	}
	public void addAttributeValue(String attributeValue) {
		this.attributeValues.add(attributeValue);
	}
	
	public boolean isSingle() {
		if(attributeValues.size() == 1)
			return true;
		else
			return false;
	}
	
	public String getSingleValue(boolean md5) {
		if(isSingle())
			if(md5)
				return convertAttributeValue(attributeValues.get(0));
			else
				return attributeValues.get(0);
		else
			return null;
	}
	
	private String convertAttributeValue(String oldAttributeValue) {
		try {
			return MD5.getInstance().makeMD5(oldAttributeValue);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public void loadEmptyAttributeValues(final List<SearchObjectAttribute> emptySearchCriteria) {
		DataGetterServiceAsync dataGetterAsc = GWT.create(DataGetterService.class);
		final SearchObjectAttribute test = this;
		AsyncCallback<ArrayList<String>> callback = new AsyncCallback<ArrayList<String>>() {
			public void onFailure(Throwable caught) {
				System.out.println(caught.getMessage());
			}

			public void onSuccess(ArrayList<String> result) {
				attributeValues = result;
				test.setAttributeValues(result);
				emptySearchCriteria.add(test);
			}
		};
		dataGetterAsc.getAttributeValue(attributeName, callback);
	}
	
	public void print() {
		System.out.println("Nazwa atrybutu: " + attributeName);
		System.out.println("\tConfidence: " + confidence);
		for(String attributeValue : attributeValues) {
			System.out.println("\tWartość atrybutu: " + attributeValue);
		}
	}
}
